package app.config;

import app.system.entity.SysPermission;
import app.system.entity.SysRolePermission;
import app.system.entity.SysUser;
import app.system.entity.SysUserRole;
import app.system.mapper.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证和权限管理类
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRolePermissionMapper rolePermMapper;
    @Autowired
    private SysPermissionMapper permSysMapper;


    /**
     * 权限认证方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入权限认证---------------------------------------");
        SysUserRole userRole1 = new SysUserRole();
        SysRolePermission rolePermission = new SysRolePermission();
        //1.获取用户身份
        SysUser userSys = (SysUser) principals.getPrimaryPrincipal();
        //2.根据用户身份获取对应的角色
        userRole1.setUser_id(userSys.getUser_id());
        SysUserRole userRole = userRoleMapper.selectUserRole(userRole1);
        //3.根据对应的角色获取用户所具有的权限
        rolePermission.setRole_id(userRole.getRole_id());
        SysRolePermission rolePerm = rolePermMapper.selectRolePermissionByTage(rolePermission);
        SysPermission perm = new SysPermission();
        perm.setPermission_id(rolePerm.getPermission_id());
        SysPermission permSys = permSysMapper.selectPermissionByTage(perm);
        //4.封装用户的权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> set = new HashSet<>();
        set.add(permSys.getPermission_val());
        info.setStringPermissions(set);
        System.out.println("权限信息==============================="+set);
        //5.返回封装结果
        return info;
    }

    /**
     * 身份认证方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        SysUser userSys = userMapper.selectUserByUserName(username);
        if (userSys == null)
            return null;
        return new SimpleAuthenticationInfo(userSys,userSys.getPassword(),getName());
    }
}
